CODE 127. Longest Substring Without Repeating Characters

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/11/14/2013-11-14-CODE 127 Longest Substring Without Repeating Characters/

访问原文「CODE 127. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring
without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public int lengthOfLongestSubstring(String s) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == s || "".equals(s)) {
return 0;
}
ArrayList<Character> list = new ArrayList<Character>();
int max = Integer.MIN_VALUE;
char[] cs = s.toCharArray();
for (int i = 0; i < cs.length; i++) {
if (list.isEmpty()) {
list.add(cs[i]);
} else {
int index = list.indexOf(cs[i]);
if (index == -1) {
list.add(cs[i]);
} else {
for (int j = 0; j <= index; j++) {
list.remove(0);
}
list.add(cs[i]);
}
}
if (list.size() > max) {
max = list.size();
}
}
return max;
}
Jerky Lu wechat
欢迎加入微信公众号